﻿using System;
using K3R.Data;

namespace K3R.SqlLogging {
	public enum LogType { Test = 1, Information = 2, Warning = 3, Error = 4 }

	public class Log {
		public string ConnectionString { get; set; }
		public string Source { get; set; }

		public Log(string connectionString, string source) {
			ConnectionString = connectionString;
			Source = source;
		}

		public int WriteToLog(string message, LogType type, int? number) {
			using (Connection conn = new Connection(ConnectionString, "k3r_addLog")) {
				conn.AddParameter("@type", type);
				conn.AddParameter("@source", (Source.Length > 50 ? Source.Substring(0, 50) : Source));
				conn.AddParameter("@message", message);
				conn.AddParameter("@number", number);
				conn.AddOutputID();
				return conn.ExecuteNonQuery<int>();
			}
		}

		public int WriteToLog(string message, LogType type) {
			return WriteToLog(message, type, null);
		}

		public int Info(string message) {
			return WriteToLog(message, LogType.Information);
		}

		public int Info(string format, params object[] args) {
			return Info(String.Format(format, args));
		}

		public int Warn(string message) {
			return WriteToLog(message, LogType.Warning);
		}

		public int Warn(string format, params object[] args) {
			return Warn(String.Format(format, args));
		}

		public int Error(string message) {
			return WriteToLog(message, LogType.Error);
		}

		public int Error(string format, params object[] args) {
			return Error(String.Format(format, args));
		}

		public int SqlError(int number, string message) {
			return WriteToLog(message, LogType.Error, number);
		}

		public int SqlError(int number, string format, params object[] args) {
			return SqlError(number, String.Format(format, args));
		}
	}
}
